/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年6月23日         Root.Lu
 */

package com.tianci.appstore.dataprovider;

import android.content.Context;
import android.os.RemoteException;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.PMUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_Boolean;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.TaskInfo.TASK_STATE;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.skyworth.framework.skysdk.android.SdCardChecker;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.utils.Tools;

import java.io.File;
import java.util.List;

public class AppDataProvider {
    private static AppDataProvider instance = null;

    public synchronized static AppDataProvider getInstance() {
        if (instance == null)
            instance = new AppDataProvider(CoocaaApplication.getContext());
        return instance;
    }

    private Context mContext = null;
    private LocalAppData localAppData = null;

    private AppDataProvider(Context context) {
        mContext = context;
        localAppData = new LocalAppData(mContext);
    }

    public LocalAppData getLocalData() {
        checkMainLooper();
        return localAppData;
    }

    public String getDownloadPath() {
        String path = null;
        if (SdCardChecker.isSDCardAvaiable()
                && (path = SdCardChecker.getExternalStoragePath()) != null) {
            File file = new File(path + "/coocaa_app/");
            if (!file.exists())
                file.mkdir();
            return file.getAbsolutePath() + "/";
        }
        return mContext.getDir("download",
                Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE).getAbsolutePath()
                + "/";
    }

    public AppStatus getAppStatus(String pkg, String versionCode) {
        checkMainLooper();
        if (pkg.equals("com.developer.fans") && Android.isPackageInstalled(mContext, pkg)) {
            return AppStatus.INSTALLED;
        }

        String status = AppStatus.NOT_DOWNLOADED.toString();
        try {
            switch (XServiceManager.getLitePMService().getAppInstallState(pkg)) {
                case PMUtils.INSTALL_STATE_INSTALLED:
                    status = AppStatus.INSTALLED.toString();
                    break;
                case PMUtils.INSTALL_STATE_INSTALLING:
                    status = AppStatus.INSTALLING.toString();
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        switch (AppStatus.valueOf(status)) {
            case INSTALLING:
            case UNINSTALLING:
                return AppStatus.valueOf(status);
            default:
                break;
        }
        List<DownloadTask> list = null;
        try {
            list = XServiceManager.getDownloaderService().getTaskList();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                DownloadExtra extra = DownloadExtra.parseJObject(list.get(i).extra,
                        DownloadExtra.class);
                if (extra.pkgname.equals(pkg)) {
                    // RemoteDownloaderTask task = list.get(i);
                    TASK_STATE state = list.get(i).info.state;
                    LogUtils.d("status", extra.title + " TASK_STATE:" + state);
                    switch (state) {
                        case READY:
                            return AppStatus.WAITING;
                        case PROCESSING:
                            return AppStatus.DOWNLOADING;
                        case STOPED:
                            return AppStatus.DOWNLOAD_PAUSED;
                        case FINISH:
                            return AppStatus.DOWNLOADED;
                        default:
                            return AppStatus.WAITING;
                    }
                }
            }
        }
        AppInfo localInfo = null;
        try {
            localInfo = XServiceManager.getLitePMService().getAppInfo(pkg);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (localInfo != null && localInfo.versionCode > 0) {
            long newVersion = Tools.getVersionFromString(versionCode);
            long oldVersion = localInfo.versionCode;
            // long oldVersion = Tools.getVersionFromString(localInfo.versionName);
            LogUtils.d("liqiwen", "getAppStatus--pkg--newVersion---oldVersion--"+pkg+"  " + newVersion + "  "
                    + oldVersion);
            if (newVersion > oldVersion) {
                if(localInfo.isSystemApp)
                    return AppStatus.HAS_NEW_VERSION_WITH_CAN_NOT_BE_UNINSTALLED;
                LiteURI uri = LiteURI.create("apps://com.coocaa.app/recovery_app?pkg=" + pkg);
                RP_Boolean b = null;
                try {
                    String r = LiteContentServiceConnecter.getService().call(uri.toString());
                    b = RP_Boolean.parseJObject(r, RP_Boolean.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (b != null && b.resource)
                    return AppStatus.HAS_NEW_VERSION_WITH_CAN_NOT_BE_UNINSTALLED;
                return AppStatus.HAS_NEW_VERSION;
            } else {
                if(localInfo.isSystemApp)
                    return AppStatus.INSTALLED_WITH_CAN_NOT_BE_UNINSTALLED;
                LiteURI uri = LiteURI.create("apps://com.coocaa.app/recovery_app?pkg=" + pkg);
                RP_Boolean b = null;
                try {
                    String r = LiteContentServiceConnecter.getService().call(uri.toString());
                    b = RP_Boolean.parseJObject(r, RP_Boolean.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (b != null && b.resource)
                    return AppStatus.INSTALLED_WITH_CAN_NOT_BE_UNINSTALLED;
                return AppStatus.INSTALLED;
            }
        }
        return AppStatus.NOT_DOWNLOADED;
    }

    public AppStatus getDownloadStatus(String id, String pkg) {
        checkMainLooper();
        String status = AppStatus.NOT_DOWNLOADED.toString();
        try {
            switch (XServiceManager.getLitePMService().getAppInstallState(pkg)) {
                case PMUtils.INSTALL_STATE_INSTALLING:
                    status = AppStatus.INSTALLING.toString();
                    break;
                default:
                    break;
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        switch (AppStatus.valueOf(status)) {
            case INSTALLING:
            case UNINSTALLING:
                return AppStatus.valueOf(status);
            default:
                break;
        }
        List<DownloadTask> list = null;
        try {
            list = XServiceManager.getDownloaderService().getTaskList();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                DownloadExtra extra = DownloadExtra.parseJObject(list.get(i).extra,
                        DownloadExtra.class);
                if (extra.pkgname.equals(pkg)) {
                    TASK_STATE state = list.get(i).info.state;
                    LogUtils.d("status", extra.title + " TASK_STATE:" + state);
                    switch (state) {
                        case READY:
                            return AppStatus.WAITING;
                        case PROCESSING:
                            return AppStatus.DOWNLOADING;
                        case STOPED:
                            return AppStatus.DOWNLOAD_PAUSED;
                        case FINISH:
                            return AppStatus.DOWNLOADED;
                        default:
                            return AppStatus.WAITING;
                    }
                }
            }
        }
        return AppStatus.NOT_DOWNLOADED;
    }

    public AppStatus isAppInstalled(String pkg) {
        boolean isInstalled = false;
        try {
            isInstalled = XServiceManager.getLitePMService().isInstalled(pkg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isInstalled)
            return AppStatus.INSTALLED;
        else
            return AppStatus.NOT_DOWNLOADED;
    }

    private void checkMainLooper() {
        // Looper looper = Looper.myLooper();
        // if (looper == Looper.getMainLooper())
        // throw new RuntimeException("Don't call this function in main thread!!! ----luyx");
    }
}
